package com.learning.servlet2x.config;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * ClassName: ServletConfigServlet
 * Description: Servlet 配置
 * Date: 2018/6/23 22:41 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ServletConfigServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("带参数的init方法，先调用");
        // 这句一定要写，不然不会装载 ServletConfig 对象
        super.init(config);
    }

    @Override
    public void init() throws ServletException {
        System.out.println("无参的init方法，后调用");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取 ContextPath
        String contextPath = req.getContextPath();
        System.out.println("上下文路径 contextPath： " + contextPath);

        // 直接通过父类封装的 getInitParameter 方法
        String user = super.getInitParameter("user");
        System.out.println("ServletConfigServlet 初始化参数 user 的值： " + user);

        // 使用 ServletConfig 内部的 getInitParameter 方法
        String user1 = super.getServletConfig().getInitParameter("user");
        System.out.println("ServletConfigServlet 初始化参数 user 的值： " + user1);

        Enumeration parameterNames = super.getInitParameterNames();
        while (parameterNames.hasMoreElements()) {
            String thisName = parameterNames.nextElement().toString();
            System.out.println("初始化参数 ： " + thisName);
        }

        final ServletContext servletContext = super.getServletContext();
        System.out.println(servletContext.getAttribute("newUser"));
    }
}
